package com.horizon.common.controller;

import com.horizon.common.annotation.NoSync;
import com.horizon.common.entity.BaseEntity;
import com.horizon.common.service.IBaseService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 自动从数据库同步实体信息切面
 *
 * @author wangfuwei
 * @version 2018-08-10
 */
@Aspect
@Component
public class SyncEntityAspect {

    @Autowired
    private IBaseService baseService;

    @Pointcut("target(com.horizon.common.controller.IBaseController)")
    public void pointcut() {

    }

    /**
     * 自动从数据库同步信息
     *
     * @param joinPoint
     */
    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        Object[] args = joinPoint.getArgs();

        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];

            if (arg != null && arg instanceof BaseEntity) {
                List<Class> annotationList = new ArrayList<>();
                for (Annotation annotation : parameterAnnotations[i]) {
                    annotationList.add(annotation.annotationType());
                }

                if (!annotationList.contains(NoSync.class)) {
                    baseService.syncEntity((BaseEntity) arg);
                }
            }
        }
    }
}
